﻿using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Tmp.Models;

namespace Tmp.Controllers;

[Route("upload")]
public class FileUploadController: Controller
{
    private readonly string _uploadPath;// 设置文件上传的目标路径
    private readonly long _maxFileSize;

    private DownloadLimit _limit;
    public FileUploadController(IOptions<Configuration> config,DownloadLimit limit)
    {
        _maxFileSize = config.Value.MaxFileSize;
        _uploadPath = config.Value.UploadPath;
        _limit = limit;
    }
    [HttpPost("multiple/{hash}")]
    public async Task<IActionResult> UploadMultipleFiles(List<IFormFile> files,int hash)
    {
        try
        {
            var builder = new StringBuilder();
            long size = 0;
            foreach (var formFile in files)
            {
                size += formFile.Length;
                builder.Append(formFile.FileName+formFile.Length);
                if (formFile.Length > _maxFileSize)
                {
                    return BadRequest("至少存在一个文件，该文件体积过大");
                }
            }

            if (size > _limit.CurrentDownload)
            {
                return BadRequest("达到文件上传限制，请尝试小的文件，或者联系管理员.");
            }

            //builder.Append(DateTime.Now.Hour);
            var calHash = builder.ToString().GetHashCode();
            if (calHash != hash)
            {
                return BadRequest("不允许非法上传文件");
            }
            if(Directory.Exists(Path.Combine(_uploadPath,""+calHash)))
            {
                // 无需上传，已经存在相关文件组
            }
            else
            {
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        var filePath = Path.Combine(_uploadPath,""+calHash, file.FileName);
                        var directoryPath = Path.GetDirectoryName(filePath);

                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }
                        await using var stream = new FileStream(filePath, FileMode.Create);
                        await file.CopyToAsync(stream);
                        _limit.CurrentDownload -= file.Length;
                    }
                }
            }


            return Ok("文件上传成功");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"文件上传失败: {ex.Message}");
        }
    }

}